package com.ybliang.plat.common.autoconfig.webapp.interceptor;

import com.ybliang.plat.common.web.annotation.IgnoreAuthentication;
import com.ybliang.plat.common.web.interceptor.AbstractPlatInterceptor;
import com.ybliang.plat.serviceapp.common.exception.BusinessException;
import com.ybliang.plat.serviceapp.common.exception.Errors;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 论证拦截器
 * @author liangyb
 *
 */
@Component
public class AuthenticationInterceptor extends AbstractPlatInterceptor {

	private static Logger LOGGER = LoggerFactory.getLogger(AuthenticationInterceptor.class);

	private static final String ACCESS_TOKEN = "AccessToken";

	private static List<String> ignoreUrlsMatchers = new ArrayList<String>();

	static{

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if(isIgnoreUrl(request)){
			return true;
		}

		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		if(handlerMethod.getBeanType() == BasicErrorController.class) {
			return true;
		}

		Method method        = handlerMethod.getMethod();
		//检查是否有IgnoreAuthentication注解，有则跳过认证
		if (method.isAnnotationPresent(IgnoreAuthentication.class)) {
			return true;
		}
		if(method.getDeclaringClass().isAnnotationPresent(IgnoreAuthentication.class)){
			return true;
		}

		String token = request.getHeader(ACCESS_TOKEN);

		//判断token不能为空
		if(Strings.isBlank(token)){
			String servletPath = request.getServletPath();
			throw new BusinessException(Errors.SystemError.MISS_TOKEN, "servletPath -> " + servletPath);
		}

		return true;
	}


	/**
	 * permissionUrl转化为RequestMapping
	 * @param permissionUrl
	 * @return
	 */
	private String toRequestMappingUrl(String permissionUrl) {
		if(StringUtils.isBlank(permissionUrl)) {
			return "";
		}
		permissionUrl = permissionUrl.trim();
		if(!permissionUrl.startsWith("/")) {
			permissionUrl = "/v1/" + permissionUrl;
		}
		return permissionUrl;
	}




	public   boolean isAdminstartorUser(String userName) {
		
		String adminstartorUsername = "openAdmin";

		if (StringUtils.isBlank(userName)) {
			return false;
		}
		if (ObjectUtils.equals(adminstartorUsername, userName)) {
			return true;
		}
		
		return false;
	}
	
	private static boolean isIgnoreUrl(HttpServletRequest request){

		return false;
	}

}
